/*
 * $Id: UserController.java 46 2013-05-03 21:38:12Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 46 $
 * $Date: 2013-05-03 21:38:12 +0000 (Fri, 03 May 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.sci.logisticsmap.web.controller.admin;

import com.sci.logisticsmap.service.UserLogService;
import com.sci.logisticsmap.service.UserService;
import com.sci.logisticsmap.service.model.UserLogDTModel;
import com.sci.logisticsmap.support.Page;
import com.sci.logisticsmap.service.model.UserDTModel;
import com.sci.logisticsmap.service.model.UserDTCommand;
import com.sci.logisticsmap.web.support.WebUtilities;
import com.sci.logisticsmap.web.model.UserVWCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.PostConstruct;

/**
 * The Controller for processing user admin view/ajax requests.
 *
 * @author gabakyan@gmail.com (Last modified by $Author: gabakyan $)
 * @version $Revision: 46 $
 */
@Controller("admin.UserController")
@RequestMapping("")
public class UserController extends BaseController {
    /**
     * The user admin path.
     */
    public static final String PATH_ADMIN_USER = "/admin/user";
    /**
     * The user edit admin path.
     */
    public static final String PATH_ADMIN_USER_EDIT = "/admin/user/edit";
    /**
     * The user list admin path.
     */
    public static final String PATH_ADMIN_USER_LIST = "/admin/user/list";

    /**
     * The user log admin path.
     */
    public static final String PATH_ADMIN_USER_LOG = "/admin/user/log";
    /**
     * The user log list admin path.
     */
    public static final String PATH_ADMIN_USER_LOG_LIST = "/admin/user/log/list";

    /**
     * The user edit admin view.
     */
    private final String viewEdit = "/admin/user/editPage";
    /**
     * The user list admin view.
     */
    private final String viewList = "/admin/user/listPage";

    /**
     * The user log list admin view.
     */
    private final String viewLogList = "/admin/user/log/listPage";

    /**
     * The user service.
     */
    @Autowired
    private UserService userService;
   /**
    * The user log service.
    */
    @Autowired
    private UserLogService userLogService;

    /**
     * The default constructor.
     * Initializes a Controller class.
     */
    public UserController() {
    }

    /*
     * (non-Javadoc)
     *
     * @see BaseController#init()
     */
    @PostConstruct
    public void init() {
        super.init();
    }

    /**
     * The method to response on the user edit admin view request.
     * @param  username
     *         The username.
     * @param  model
     *         The model.
     *
     * @return the user edit admin view.
     */
    @RequestMapping(value=PATH_ADMIN_USER_EDIT, method=RequestMethod.GET)
    public String onEdit(@RequestParam(value="username") String username, Model model) {
        try {
            addUserStatusSelectOptionsToModel(model);

            UserDTCommand userCommand = userService.getDTCommand(username);
            model.addAttribute("userCommand", conversionUtilities.convert(userCommand, UserVWCommand.class));
        } catch (Exception e) {
            addExceptionToModel(model, e);
        }

        return viewEdit;
    }

    /**
     * The method to response on the user edit admin view submitting request.
     * @param  command
     *         The command.
     * @param  result
     *         The validation binding result.
     * @param  model
     *         The model.
     *
     * @return the user edit admin view.
     */
    @RequestMapping(value=PATH_ADMIN_USER_EDIT, method=RequestMethod.POST)
    public String onEditSubmit(@ModelAttribute("userCommand") UserVWCommand command, BindingResult result, Model model) {
        try {
            boolean failed = false;
            if (!result.hasErrors()) {
                try {
                    userService.edit(conversionUtilities.convert(command, UserDTCommand.class));
                    return buildRedirectToPath(PATH_ADMIN_USER_LIST);
                } catch (Exception e) {
                    addExceptionToModel(model, e);
                    failed = true;
                }
            } else {
                failed = true;
            }

            if (failed) {
                addUserStatusSelectOptionsToModel(model);
            }
        } catch (Exception e) {
            addExceptionToModel(model, e);
        }

        return viewEdit;
    }

    /**
     * The method to response on the user list admin view request.
     *
     * @param  page
     *         The page number.
     * @param  keyword
     *         The keyword.
     * @param  model
     *         The model.
     *
     * @return the user list admin view.
     */
    @RequestMapping(value={PATH_ADMIN_USER, PATH_ADMIN_USER_LIST}, method={RequestMethod.GET})
    public String onList(@RequestParam(value="page", required=false) Integer page,
                         @RequestParam(value="keyword", required=false) String keyword, Model model) {
        try {

//    if (!StringUtils.isNotBlank(keyword)) {
//        PagedListHolder productList = new PagedListHolder(this.petStore.searchProductList(keyword.toLowerCase()));
//        productList.setPageSize(4);
//        request.getSession().setAttribute("SearchProductsController_productList", productList);
//        return new ModelAndView("SearchProducts", "productList", productList);
//    }
//    else {
//        String page = request.getParameter("page");
//        PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("SearchProductsController_productList");
//        if (productList == null) {
//            return new ModelAndView("Error", "message", "Your session has timed out. Please start over again.");
//        }
//        if ("next".equals(page)) {
//            productList.nextPage();
//        }
//        else if ("previous".equals(page)) {
//            productList.previousPage();
//        }
//        return new ModelAndView("SearchProducts", "productList", productList);
//    }

            Page<UserDTModel> userPage = userService.getDTModels(WebUtilities.validatePageRequestParam(page));
            model.addAttribute("userPage", userPage);
        } catch (Exception e) {
            addExceptionToModel(model, e);
        }

        return viewList;
    }

    /**
     * The method to response on the user log list admin view request.
     *
     * @param  page
     *         The page number.
     * @param  keyword
     *         The keyword.
     * @param  model
     *         The model.
     *
     * @return the user log list admin view.
     */
    @RequestMapping(value={PATH_ADMIN_USER_LOG, PATH_ADMIN_USER_LOG_LIST}, method={RequestMethod.GET})
    public String onLogList(@RequestParam(value="page", required=false) Integer page,
                            @RequestParam(value="keyword", required=false) String keyword, Model model) {
        try {
            addUserLogTypeToMessageCodesToModel(model);

            Page<UserLogDTModel> userLogPage = userLogService.getDTModels(WebUtilities.validatePageRequestParam(page));
            model.addAttribute("userLogPage", userLogPage);
        } catch (Exception e) {
            addExceptionToModel(model, e);
        }

        return viewLogList;
    }

    /**
     * Adds the user status select options to the model.
     *
     * @param  model
     *         The model.
     */
    private void addUserStatusSelectOptionsToModel(Model model) {
        model.addAttribute("userStatusSelectOptions", WebUtilities.getUserStatusSelectOptions());
    }

    /**
     * Adds the user log type to message codes map to the model.
     *
     * @param  model
     *         The model.
     */
    private void addUserLogTypeToMessageCodesToModel(Model model) {
        model.addAttribute("userLogTypeToMessageCodes", WebUtilities.getUserLogTypeToMessageCodes());
    }
}
